package pizzadroid.googlecode.com;

import resturant.pizzadroid.googlecode.com.Resturant;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class Database {
	private static final String CREATE_FAVORITES = "CREATE TABLE favorites (" +
													"id INTEGER PRIMARY KEY AUTOINCREMENT," +
													"name TEXT);";
	private static final String TABLE_FAVORITES = "favorites";
	private static final String DATABASE_NAME = "pizzadroid";
	private static final int DATABASE_VERSION = 2;
	
	private Context context;
	private SQLiteDatabase db;
	
	public Database(Context c) {
		this.context = c;
		OpenHelper o = new OpenHelper(this.context);
		db = o.getWritableDatabase();
	}
	
	public void addFavorite(int id, String name) {
		try {
			db.execSQL("INSERT INTO " + TABLE_FAVORITES + " (id, name) VALUES (" + id + ", '"+ name +"');");
		} catch (SQLException e) {
			Log.d("DB", e.getMessage());
		}
	}
	
	public void close() {
		db.close();
	}
	
	public void addFavoritesToAdapter(FavoritesAdapter f) {
		Cursor c = db.query(TABLE_FAVORITES, new String[] {"id", "name"}, null, null, null, null, "name");
		if (c.moveToFirst()) {
			do {
				f.add(new Resturant(c.getString(0), c.getString(1)));
			} while (c.moveToNext());
		}
		if (c != null && !c.isClosed()) {
			c.close();
		}
	}
	
	private class OpenHelper extends SQLiteOpenHelper {
		public OpenHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(CREATE_FAVORITES);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS "+ TABLE_FAVORITES);
			onCreate(db);
		}
		
	}
}
